// packageI/redeem_code/index/index.js
const skinBehavior = require("../../../utils/themeSkin/skinBehavior")
const app = getApp()
var specsManage = []; // 选择池 用于排序
var optionsId = ""; // 选择后的 规格ID
Page({

  behaviors: [skinBehavior],
  /**
   * 页面的初始数据
   */
  data: {
    radioChoose:"",
    showChoose: false,
    dispatch_types: [],
    has_many_goods: [],
    goodsDescription: "",
    show: false,
    share: 0,
    language: "",
    list: [],
    carts: [],
    details: {},
    Height: '1100rpx',
    sn: "",
    nums: 0,
    index_goods: 0, //当前商品索引
    activity_gid: "",
    current_page: 1,
    last_page: 1,

    goodsPopupShow: false,
    specsShow: false,
    hand_goods_obj: {},
    carList: [],
    hand_goods_id: "",
    message_card: "",

    showKefu: false,
    customer_open: "",
    cservice: "",
    service_mobile: "",
    service_QRcode: "",

    popThumb: "",
    popTitle: "",
    popNum: 0,
    popPrice: "",
    show2: false,
    goodsInfo: {},
    specid: "",
    has_many_options: [],
    current_index: 0,

    code_id: "", //兑换码id
    id: "", //兑换码记录id
    sn_code: "", //序列号

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let language = wx.getStorageSync('langIndex');
    this.setData({
      'language': language.en,
      code_id: options.code_id || '',
      sn_code: options.sn_code || ''
    })
    if (options.share) {
      this.setData({
        share: options.share
      })
    }

    let yz_basic_info = wx.getStorageSync('yz_basic_info');
    if(yz_basic_info){
      wx.setNavigationBarTitle({
        title: yz_basic_info.home.mailInfo.name,
      })
    }


    if (options.scene) {
      let scene = decodeURIComponent(options.scene);
      console.log(scene,"===");
      if (scene) {
        var info_arr = [];
        info_arr = scene.split('&');
        console.log(info_arr,'info_arr=>>');

        for (let i = 0; i < info_arr.length; i++) {
          let chil_arr = [];
          chil_arr = info_arr[i].split('=');
          if (chil_arr[0] == 'i') {
            this.setData({
              code_id: chil_arr[1]
            });
          }
          if (chil_arr[0] == 'm') {
            app._setMid(chil_arr[1]);
          }
          if (chil_arr[0] == 's') {
            this.setData({
              sn_code: chil_arr[1]
            });
          }
        }
      }
    }else if (options.code_id || options.sn_code) {
      wx.setStorageSync('exchange_code', {
        code_id: options.code_id,
        sn_code: options.sn_code
      })
    } else {
      let {
        code_id,
        sn_code
      } = wx.getStorageSync('exchange_code');
      this.setData({
        code_id,
        sn_code
      })
    }
    this.getData()

  },



  video_handle() {
    app.tips("兑换数量最多为1")
  },
  share_handle() {
    this.onShareAppMessage()
  },
  Hidden_overlay() {
    this.setData({
      show: false
    })
  },
  change(e) {
    this.setData({
      sn: e.detail.value
    })
  },
  binding_handle() {
    app._getNetWork({
      url: app.getNetAddresss('plugin.exchange-code.api.record.bind'),
      data: {
        sn: this.data.sn
      },
      success: resdata => {
        let {
          result,
          msg,
          data
        } = resdata.data;
        app.tips(msg);
        if (result) {
          this.setData({
            sn: '',
            code_id: data.code_id,
            sn_code: data.sn
          })
          this.getData();
        }
      }
    })
  },
  getData() {
    app._getNetWork({
      url: app.getNetAddresss('plugin.exchange-code.api.list.info'),
      data: {
        id: this.data.code_id,
        sn: this.data.sn_code,
        scope: 'pass'
      },
      success: resdata => {
        let {
          result,
          msg,
          data
        } = resdata.data;
        if (result == 0) {
          return app.tips(msg);
        }
        this.setData({
          details: data,
          customer_open: data.cservice.customer_open,
          cservice: data.cservice.cservice,
          service_mobile: data.cservice.service_mobile,
          service_QRcode: data.cservice.service_QRcode,
        })
        if (data.type == 2) {
          this.setData({
            sn: data.current_code || this.data.sn_code
          })
        }
        if (data.login_status == 0) {
          this.setData({
            show: true
          })
          return;
        }
        if (this.data.share == 1) {
          this.setData({
            show: true
          });

        }
        if (data.type == 1) {
          this.getGoods({
            id: data.id
          })
          this.setData({
            sn_code: data.current_code
          })
        }
      }
    })
  },
  getGoods(json = {}) {
    app._getNetWork({
      url: app.getNetAddresss('plugin.exchange-code.api.list.goodList'),
      data: json,
      success: resdata => {
        let {
          result,
          msg,
          data
        } = resdata.data;
        if (result == 0) {
          return app.tips(msg);
        }
        this.setData({
          current_page: data.current_page,
          last_page: data.last_page
        })
        if (data.current_page == 1) {
          this.data.list = data.data.forEach(item => {
            item.count = 0;
          })
          this.setData({
            list: data.data || []
          });
          if (data.data && data.data.length <= 5) {
            this.setData({
              Height: 'auto'
            })
          }
        } else {
          data.data.forEach(item => {
            item.count = 0
          })
          let arr = data.data;

          let list = this.data.list.concat(arr);
          this.setData({
            list
          })
        }

      }
    })
  },
  getMoreData() {
    if (this.data.current_page >= this.data.last_page) {
      return;
    }
    this.getGoods({
      page: this.data.current_page + 1,
      id: this.data.code_id
    })

  },
  login() {
    wx.navigateTo({
      url: '/pages/login/login',
    })
  },
  to_list() {
    wx.navigateTo({
      url: '/packageI/redeem_code/center/center',
    })
  },
  severShowTap() {
    this.setData({
      showKefu: true
    })
  },
  check() {
    let arr = [],
      plugins_ids = [];
    this.data.list.forEach(item => {
      if (item.count >= 1) {
        // let option_id = "0";
        if (item.has_option !== 1) {
          arr.push({
            goods_id: item.id,
            total: item.count,
            option_id: item.option_id
          })
        }

        if (!plugins_ids.includes(item.plugin_id)) {
          plugins_ids.push(item.plugin_id)
        }
      }

    })
    if (this.data.has_many_goods && this.data.has_many_goods.length !== 0) {
      this.data.has_many_goods.forEach(item => {
        if (item.total >= 1) {
          arr.push({
            goods_id: item.goods_id,
            total: item.total,
            option_id: item.option_id
          })
        }
      })
    }

    let ids = [];
    ids = arr.map(item => {
      return item.goods_id
    })
    console.log(JSON.stringify(arr), "arr=>>");


    app._getNetWork({
      url: app.getNetAddresss('plugin.exchange-code.api.record.exchangeCheck'),
      data: {
        sn: this.data.sn_code,
        goods: JSON.stringify(arr)
      },
      success: resdata => {
        let {
          result,
          msg,data
        } = resdata.data;
        if (result) {
          this.getLog(ids, arr, plugins_ids)
        } else {

          if (data && data.length !== 0) {
            if (data.need_choose == 1) {
              this.setData({
                showChoose: true,
                dispatch_types: data.dispatch_types
              })
            } else {
              this.submitGoods();
            }
          } else {
            app.tips(msg)
          }
        }
      }
    })
  },
  closeChoose() {
    this.setData({
      showChoose: false
    })
  },
  toBuy() {
    this.submitGoods();
  },
  typeChange(event) {
    this.setData({
      radioChoose: Number(event.detail),
    });
  },
  // 提交订单
  submitGoods() {
    let goodsId = [],goods=[];
    if (this.data.showChoose && !this.data.radioChoose.toString()) {
      wx.showToast({
        icon: "none",
        title: "请先选择配送方式",
        duration: 1500,
      });
      return;
    }

    if (this.data.showChoose) {
      // 配送方式有冲突
      for (let i = 0; i < this.data.dispatch_types[this.data.radioChoose].member_carts.length; i++) {
        goodsId.push(
          this.data.dispatch_types[this.data.radioChoose].member_carts[i].goods_id
        );
        goods.push({
          total:this.data.dispatch_types[this.data.radioChoose].member_carts[i].total,
          goods_id:this.data.dispatch_types[this.data.radioChoose].member_carts[i].goods_id,
          option_id:this.data.dispatch_types[this.data.radioChoose].member_carts[i].option_id,
        })
      }
    }
    goodsId = goodsId.join(",")
    goods = JSON.stringify(goods)


    app._getNetWork({
      url: app.getNetAddresss('plugin.exchange-code.api.log.create'),
      data: {
        id: this.data.sn_code
      },
      success: resdata => {
        let {
          result,
          msg,
          data
        } = resdata.data;
        if (result == 0) {
          return app.tips(msg);
        }
        let url_params = `tag=exchange_code&goodsId=${goodsId}&goods=${goods}&current_code=${this.data.details.code}&name=${this.data.details.name}&exchange_code_id=${data.exchange_code_id}`
        wx.navigateTo({
          url: `/packageD/buy/myOrder_v2/myOrder_v2?${url_params}`
        });
      }

    })



  },
  // 界面选择规格触发事件
  selectSpecs(e, str, i) {
    let data = {};
    let id = 0;

    if (str == "first") {
      data = e;
      id = e.id;
    } else {
      data = e.target.dataset.item || e.currentTarget.dataset.item;

      id = e.target.dataset.id || e.currentTarget.dataset.id;
    }

    // 处理选择池
    this.manageSpecs(data);

    // 处理规格组合选择状态
    this.setGoodsSpecs(data);

    // 设置选择规格后的 价格、照片、库存
    this.setGoodsSpecsChangeInfo(id);

  },

  // 处理选择池
  manageSpecs(data) {
    var specsObject = {};
    specsObject.id = data.id;
    specsObject.specid = data.specid;
    specsObject.title = data.title;

    if (specsManage.length > 0) {
      for (let i = 0; i < specsManage.length; i++) {
        if (specsManage[i].specid == specsObject.specid) {
          specsManage.splice(i, 1);
        }
      }
      specsManage.push(specsObject);
    } else {
      specsManage.push(specsObject);
    }

    // 排序
    if (specsManage.length == this.data.goodsInfo.has_many_specs.length) {
      var newSpecsManage = [];
      for (let i = 0; i < this.data.goodsInfo.has_many_specs.length; i++) {
        for (let j = 0; j < specsManage.length; j++) {
          if (this.data.goodsInfo.has_many_specs[i].id == specsManage[j].specid) {
            newSpecsManage.push(specsManage[j]);
            break;
          }
        }
      }
      specsManage = newSpecsManage;
    }
    this.setGoodsDescription();
  },

  // 处理goodsDescription 数据
  setGoodsDescription() {
    var description = "";
    // 相等代表全选了 体现语句
    if (specsManage.length == this.data.goodsInfo.has_many_specs.length) {
      description = "已选择 ";
      for (let i = 0; i < specsManage.length; i++) {
        description += specsManage[i].title + " ";
      }
      this.setData({
        goodsDescription: description,
      });
    } else {
      description = "请选择 ";

      for (let i = 0; i < this.data.goodsInfo.has_many_specs.length; i++) {
        for (let j = 0; j < specsManage.length; j++) {
          if (this.data.goodsInfo.has_many_specs[i].id != specsManage[j].specid) {
            description += this.data.goodsInfo.has_many_specs[i].title + " ";
            break;
          }
        }
      }
      this.setData({
        goodsDescription: description,
      });
    }
  },

  // 处理规格组合选择状态 过滤数据
  setGoodsSpecs(specs) {
    for (let i = 0; i < this.data.goodsInfo.has_many_specs.length; i++) {
      if (specs.specid != this.data.goodsInfo.has_many_specs[i].id) {
        this.setGoodsSpecsStatus(this.data.goodsInfo.has_many_specs[i].specitem, specs.id);
      }
    }
  },

  // 处理规格组合选择状态 处理状态 specitem 组合数组(未选中的) id当前选中的ID 根据ID 组合算是否有当前组合
  setGoodsSpecsStatus(specitem, id) {
    let options = []; // 数据池

    for (let i = 0; i < this.data.goodsInfo.has_many_options.length; i++) {
      let _specs = this.data.goodsInfo.has_many_options[i].specs.split("_");
      // 判断是否包含
      for (let j = 0; j < _specs.length; j++) {
        if (_specs[j] == id) {
          options.push(this.data.goodsInfo.has_many_options[i]);
        }
      }
    }

    for (let m = 0; m < options.length; m++) {
      let _specs = options[m].specs.split("_");
      for (let y = 0; y < _specs.length; y++) {
        if (_specs[y] != id && options[m].stock == 0) {
          for (let n = 0; n < specitem.length; n++) {
            if (_specs[y] == specitem[n].id) {
              specitem[n].c = true;
            }
          }
        } else if (_specs[y] != id && options[m].stock > 0) {
          for (let n = 0; n < specitem.length; n++) {
            if (_specs[y] == specitem[n].id) {
              specitem[n].c = false;
            }
          }
        }
      }
    }
  },

  // 设置选择规格后的 价格、照片、库存
  setGoodsSpecsChangeInfo(id) {
    let popPrice = "";
    // 根据ID 排序 specsManage.sort()
    specsManage.sort(function (a, b) {
      return a.id - b.id;
    });
    if (specsManage.length === this.data.goodsInfo.has_many_specs.length) {
      let goodsSpecs = "";
      for (let j = 0; j < specsManage.length; j++) {
        goodsSpecs += specsManage[j].id + "_";
      }
      goodsSpecs = goodsSpecs.substring(0, goodsSpecs.length - 1); // 处理"_"
      this.setData({
        specid: goodsSpecs,
      });
      for (let i = 0; i < this.data.goodsInfo.has_many_options.length; i++) {
        if (goodsSpecs === this.setGoodsSpecsBySort(this.data.goodsInfo.has_many_options[i].specs)) {
          if (this.data.goodsInfo.point_goods) {
            popPrice = this.data.goodsInfo.point_goods.point_option[i].goods_point; //设置默认价格
          } else {
            popPrice = this.data.goodsInfo.has_many_options[i].product_price; //设置默认价格
          }
          console.log(popPrice, "popPrice-434");
          this.setData({
            popPrice: popPrice, // 设置价格
          });


          let popThumb = app._isTextEmpty(this.data.goodsInfo.has_many_options[i].thumb) ? this.data.goodsInfo.thumb : this.data.goodsInfo.has_many_options[i].thumb; // 设置图片
          this.setData({
            popThumb,
          });

          optionsId = this.data.goodsInfo.has_many_options[i].id; // 设置规格ID，用于生成订单
          break;
        }
      }

    } else {
      let goodsSpecs = "";
      for (let j = 0; j < specsManage.length; j++) {
        goodsSpecs += specsManage[j].id + "_";
      }
      this.setData({
        specid: goodsSpecs,
      });
    }

    let _goods = this.data.has_many_goods.filter(item => item.option_id == optionsId)
    console.log(optionsId, "optionsId====");
    console.log(_goods, "_goods===-501");
    if (_goods.length == 0) {
      this.setData({
        popNum: 0
      })
    } else {
      this.setData({
        popNum: _goods[0].total
      })
    }

  },

  // 处理商品goodsSpecs 并排序 新方法
  setGoodsSpecsBySort(specs) {
    let _specs = specs.split("_"); // 先变成数组
    // _specs.sort();//排序
    _specs.sort(function (a, b) {
      return a - b;
    });

    // 在组装回去
    let goodsSpecs = "";
    for (let j = 0; j < _specs.length; j++) {
      goodsSpecs += _specs[j] + "_";
    }
    goodsSpecs = goodsSpecs.substring(0, goodsSpecs.length - 1); // 处理"_"

    return goodsSpecs;
  },

  getLog(goodsId, arr, plugins_ids) {
    app._getNetWork({
      url: app.getNetAddresss('plugin.exchange-code.api.log.create'),
      data: {
        id: this.data.sn_code
      },
      success: resdata => {
        let {
          result,
          msg,
          data
        } = resdata.data;
        if (result == 0) {
          return app.tips(msg);
        }

        if (plugins_ids.includes(46)) { //活动报名商品
          let _arr = this.data.list.filter(item => {
            if (item.count >= 1) {
              return item
            }
          })
          wx.navigateTo({
            url: `/packageC/Myshaky/enrollEnter/enrollEnter?id=${_arr[0].relation_id}&exchange_code_id=${data.exchange_code_id}`,
          })
        }

        if (plugins_ids.includes(113)) { //多企业项目核销商品
          let total = this.goods_total();
          let urlStr = `/packageD/buy/myOrder_v2/myOrder_v2?tag=store_projects_goods&exchange_code_id=${data.exchange_code_id}&goodsId=${goodsId[0]}&total=${total}`
          if(this.data.details.show_info==1){
            urlStr+='&current_code='+this.data.details.code+'&name='+this.data.details.name;
          }
          wx.navigateTo({
            url:urlStr
          });
        }


        if (plugins_ids.includes(140)) { //卡券商品
          let total = this.goods_total();
          let urlStr =  `/packageD/buy/myOrder_v2/myOrder_v2?optionsId=${optionsId}&total=${total}&tag=-2&exchange_code_id=${data.exchange_code_id}&goodsId=${goodsId[0]}`
          if(this.data.details.show_info==1){
            urlStr+='&current_code='+this.data.details.code+'&name='+this.data.details.name
          }
          wx.navigateTo({
            url:urlStr
          });
        }

        if (plugins_ids.includes(101)) { //企业预约商品
          let total = this.goods_total();
          let urlStr = `/packageD/buy/myOrder_v2/myOrder_v2?total=${total}&tag=appointment_goods&exchange_code_id=${data.exchange_code_id}&goodsId=${goodsId[0]}`
          if(this.data.details.show_info==1){
            urlStr+='&current_code='+this.data.details.code+'&name='+this.data.details.name
          }
          wx.navigateTo({
            url: urlStr
          });
        }

        if (plugins_ids.includes(144)) { //消费券联盟商品
          let _optionsId = arr[0].option_id || '0';
          wx.navigateTo({
            url: `/packageF/consumption/orderAffirm/orderAffirm?goodsId=${goodsId[0]}&e_id=${data.exchange_code_id}&total=${arr[0].total}&optionsId=${_optionsId}`,
          })
        }


        if (plugins_ids.includes(0) || plugins_ids.includes(120) || plugins_ids.includes(44) || plugins_ids.includes(103)) {
          //跳转到下单页
          let urlStr = `/packageD/buy/myOrder_v2/myOrder_v2?&tag=exchange_code&exchange_code_id=${data.exchange_code_id}&goodsId=${goodsId}&goods=${JSON.stringify(arr)}`;
          if(this.data.details.show_info==1){
            urlStr+='&current_code='+this.data.details.code+'&name='+this.data.details.name
          }
          wx.navigateTo({
            url: urlStr
          });
        }

      }
    })

  },
  // 商品数量
  goods_total() {
    let total = 0;
    this.data.list.forEach(item => {
      if (item.count >= 1) {
        total += item.count;
      }
    })
    return total;
  },
  redeem() {
    if (this.data.details.type == 2) {
      app._getNetWork({
        url: app.getNetAddresss('plugin.exchange-code.api.record.levelExchange'),
        data: {
          id: this.data.sn
        },
        success: resdata => {
          let {
            result,
            msg
          } = resdata.data;
          if (result) {
            this.setData({
              show: true,
              message_card: msg,
              sn: ""
            })
          } else {
            app.tips(msg)
          }
        }
      })

    } else {
      this.check()
    }
  },
  openGoodsDetail(e) {
    if(this.data.details.show_detail==0){
      return;
    }
    let item = e.currentTarget.dataset.item;
    if (item.id == this.data.hand_goods_id) {
      this.setData({
        goodsPopupShow: true,
      });
    } else {
      this.data.hand_goods_id = item.id;
      this.getGoodsDetails(item.id, "goodsDetails");
    }
    this.setData({
      index_goods: e.currentTarget.dataset.i,
      activity_gid:item.id,
    })
  },
  goodsDetailCartAdd(evt) {
    console.log(evt,"===>>>>>>");
    this.data.list.forEach(item => {
      if(item.id == this.data.activity_gid){
        if(item.has_option == 1){
          let json = {
            currentTarget:{
              dataset:{

              }
            }
          }
          this.selectOption(item.id,i,item)
          this.setData({
            goodsPopupShow: false,
            specsShow: false,
          });
        }else{
          this.setData({
            goodsPopupShow: false,
            specsShow: true,
          });
        }
      }
    })

  },
  getGoodsDetails(id, type) {
    let urlStr = app.getNetAddresss("goods.goods.get-goods-page");
    app._postNetWork({
      url: urlStr,
      data: {
        id: Number(id)
      },
      success: (resdata) => {
        let res = resdata.data;
        if (res.result !== 1) return this.tips(res.msg);
        let name = "";
        if (type == "goodsDetails") {
          name = "goodsPopupShow";
        } else if (type == "specs") {
          name = "specsShow";
        }

        this.setData({
          [name]: true,
          hand_goods_obj: res.data.get_goods,
        });
      },
    });
  },
  submitAction() {
    if (specsManage.length < this.data.goodsInfo.has_many_specs.length) {
      // 请选择规格
      this.setData({
        show2: false,
      });
      wx.showToast({
        title: this.data.goodsDescription,
        icon: "none",
      });
      return;
    }
    let count = this.data.popNum + 1;
    this.data.has_many_goods.push({
      option_id: optionsId,
      goods_id: this.data.list[this.data.current_index].id,
      total: 1
    })
    if (this.data.details.single_order == 1) { //单选
      if (this.data.has_many_goods && this.data.has_many_goods.length !== 0) {
        let has_many_goods = this.data.has_many_goods.filter(item => {
          if (item.goods_id == this.data.list[this.data.current_index].id) {
            return item;
          }
        })
        this.data.has_many_goods = has_many_goods
      }
      this.data.list.forEach(item => {
        if (item.id !== this.data.list[this.data.current_index].id) {
          item.count = 0;
        }
      })
    } else {
      this.data.list.forEach(item => {
        if (item.id === this.data.list[this.data.current_index].id) {
          item.count = 1;
        }
      })
    }

    console.log(this.data.has_many_goods, "this.data.has_many_goods");
    this.setData({
      has_many_goods: this.data.has_many_goods,
      list: this.data.list,
      popNum: count
    })


    this.updateNums()
  },
  updateNums() {
    let nums1 = 0;
    if (this.data.has_many_goods && this.data.has_many_goods.length !== 0) {
      this.data.has_many_goods.forEach(item => {
        if (item.goods_id == this.data.list[this.data.current_index].id) {
          nums1 += item.total
        }
      })
      this.data.list[this.data.current_index].count = nums1;
    }

    let nums = 0;
    this.data.list.forEach(item => {
      nums += item.count
    })
    this.setData({
      nums,
      list: this.data.list
    })
    if (this.data.nums > this.data.details.exchange_limit) {
      app.tips("选择的数量已经超过兑换数量限制，请取消后再重新选择！")
    }
  },
  close() {
    this.setData({
      show2: false
    })
  },

  close_yz_specs_popup(e) {
    if (e.detail.clicktype == 1) {

      this.data.carts.forEach(item => {
        if (item.id == this.data.activity_gid) {
          item.total = e.detail.goodsCount
          item.option_id = e.detail.optionsId
        } else {
          item.total = 0;
          item.option_id = '0';
        }
      })
      this.data.list.forEach((item, index) => {
        if (item.id == this.data.activity_gid) {
          item.option_id = e.detail.optionsId
        } else if (item.has_option == 0) {
          item.option_id = '0';
        }
        if (this.data.details.single_order == 1) { //单选
          if (item.id == this.data.activity_gid) {
            this.data.list[index].count = e.detail.goodsCount;
          } else {
            this.data.list[index].count = 0;
          }
        } else { //多选
          if (item.id == this.data.activity_gid) {
            this.data.list[index].count = e.detail.goodsCount;
          }
        }
      })


      let nums = 0;
      this.data.list.forEach(item_2 => {
        nums += item_2.count
      })



      this.setData({
        specsShow: false,
        nums,
        list: this.data.list,
        carts: this.data.carts
      });

    } else {
      this.setData({
        specsShow: false,
      });
    }
  },
  // 多规格购物车
  selectOption(e) {
    console.log(e);
    optionsId = "";
    specsManage = [];
    let item = e.currentTarget.dataset.item;
    let index = e.currentTarget.dataset.index;
    this.setData({
      specid: '',
      current_index: index,
      activity_gid: item.id,
      popTitle: item.title,
      popPrice: item.price,
      popThumb: item.thumb,
      show2: true,
      popNum: 0,
    })

    let urlStr = app.getNetAddresss("goods.goods.get-goods-page");
    app._postNetWork({
      url: urlStr,
      data: {
        id: Number(item.id)
      },
      success: resdata => {
        let res = resdata.data;
        if (res.result !== 1) return this.tips(res.msg);
        this.setData({
          goodsInfo: res.data.get_goods,
          has_many_options: this.data.has_many_options.concat(res.data.get_goods.has_many_options)
        });
        if (!this.data.specid.length) {
          let popPrice = this.data.goodsInfo.min_price + "-" + this.data.goodsInfo.max_price; // 设置默认价格
          if (this.data.goodsInfo.point_goods) {
            popPrice = this.data.goodsInfo.point_goods.min_point + "-" + this.data.goodsInfo.point_goods.max_point; //设置默认价格
          }
          this.setData({
            popPrice: popPrice,
          });
        }
        this.setData({
          goodsDescription: "请选择",
        });
        let goodsDescription;
        for (let i = 0; i < this.data.goodsInfo.has_many_specs.length; i++) {
          goodsDescription = this.data.goodsDescription;
          goodsDescription += "" + this.data.goodsInfo.has_many_specs[i].title;
        }
        this.setData({
          goodsDescription,
        });

        if (!this.data.optionsId) {
          // 默认选择第一个
          for (let i = 0; i < this.data.goodsInfo.has_many_specs.length; i++) {
            if (this.data.goodsInfo.goods_option_ids && this.data.goodsInfo.goods_option_ids.length >= 0) {
              for (let j = 0; j < this.data.goodsInfo.has_many_specs[i].specitem.length; j++) {
                if (this.data.goodsInfo.has_many_specs[i].specitem[j].id == Number(this.data.goodsInfo.goods_option_ids[i])) {
                  this.selectSpecs(this.data.goodsInfo.has_many_specs[i].specitem[j], "first", i);
                }
              }
            } else {
              this.selectSpecs(this.data.goodsInfo.has_many_specs[i].specitem[0], "first", i);
            }
          }
        }

      }
    })
    // this.showGoodPup(item.id, true, item, index);
  },
  showGoodPup(_id, status, _item, i) {

    if (this.data.carts && this.data.carts.length !== 0) {
      this.data.carts.forEach(item => {
        if (item.id !== _id) {
          this.data.carts.push({
            ..._item,
            total: this.data.list[i].count,
            goods_id: _item.id
          });
        }
      })
      this.setData({
        carts: this.data.carts
      })
    } else {
      this.data.carts.push({
        ..._item,
        total: this.data.list[i].count,
        goods_id: _item.id
      });
      this.setData({
        carts: this.data.carts
      })
    }
    this.setData({
      activity_gid: _id,
      index_goods: i
    })

    if (_id == this.data.hand_goods_id) {
      this.setData({
        specsShow: true,
      });
    } else {
      this.data.hand_goods_id = _id;
      this.getGoodsDetails(_id, "specs");
    }
  },
  changeAddCount(e) {
    let index = e.currentTarget.dataset.i;
    let popNum = 0;
    if (index == 1) {
      popNum = this.data.popNum + 1;
      this.data.has_many_goods.forEach(item => {
        if (item.option_id == optionsId) {
          item.total = popNum;
        }
      })
    } else {
      if (this.data.popNum == 0) {
        this.data.has_many_goods.forEach(item => {
          if (item.option_id == optionsId) {
            item.total = 0
          }
        })
      } else {
        popNum = this.data.popNum - 1;
        this.data.has_many_goods.forEach(item => {
          if (item.option_id == optionsId) {
            item.total = popNum
          }
        })
      }
    }
    this.setData({
      popNum,
      list: this.data.list,
      has_many_goods: this.data.has_many_goods
    })
    this.updateNums();

  },
  reduceCartNum(e) {
    let cartid = e.currentTarget.dataset.cartid;
    this.data.list.forEach((chi, index) => {
      if (chi.id == cartid) {
        if (chi.count == 1) {
          this.data.list[index].count = 0;
        } else {
          this.data.list[index].count -= 1;
        }
      }
    })
    this.setData({
      list: this.data.list,
      nums: this.data.nums - 1
    })

    if (this.data.nums > this.data.details.exchange_limit) {
      app.tips("选择的数量已经超过兑换数量限制，请取消后再重新选择！")
    }

  },
  addCartNum(e) {
    let cartid = e.currentTarget.dataset.cartid;
    this.data.list.forEach((chi, index) => {
      if (chi.id == cartid) {
        this.data.list[index].count += 1
      }
    })
    this.setData({
      list: this.data.list,
      nums: this.data.nums + 1
    })
    if (this.data.nums > this.data.details.exchange_limit) {
      app.tips("选择的数量已经超过兑换数量限制，请取消后再重新选择！")
    }
  },
  get_specification(id){
    return new Promise((resolve,reject)=>{
      app._getNetWork({
        url:app.getNetAddresss("goods.goods.get-goods-page"),
        data:{id:Number(id)},
        success:resdata=>{
          let {result,data} = resdata.data;
          if(result){
            if(data.get_goods.has_many_options && data.get_goods.has_many_options.length!==0){
              resolve(data.get_goods.has_many_options[0].id)
            }else{
              resolve(0)
            }
          }else{
            reject()
          }
        }
      })
    })
  },
  async cart(e) {
    let item = e.currentTarget.dataset.item;
    let option_id = 0;
    optionsId = '';
    if(item.has_option!==2){
       option_id =  await this.get_specification(item.id);
    };

    if (this.data.details.single_order == 1) {
      this.setData({
        specid: '',
        has_many_goods: []
      })
    }

    this.data.list.forEach((chi, index) => {
      if (this.data.details.single_order == 1) { //单选
        if (item.id == chi.id) {
          this.data.list[index].count = 1;
          this.data.list[index].option_id = option_id;
        } else {
          this.data.list[index].count = 0;
          this.data.list[index].option_id = option_id;
        }
      } else { //多选
        if (item.id == chi.id) {
          this.data.list[index].count = 1;
          this.data.list[index].option_id = option_id;
        }
      }

    })
    this.updateNums()
    // this.data.list.forEach(item_2 => {
    //   nums += item_2.count
    // })


    // this.setData({
    //   list: this.data.list,
    //   nums
    // })
    // if (this.data.nums > this.data.details.exchange_limit) {
    //   app.tips("选择的数量已经超过兑换数量限制，请取消后再重新选择！")
    // }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {



  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.setData({showChoose:false})
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    if(this.data.share == 1){
      let {
        title,
        imgUrl,
        description
      } = wx.getStorageSync("wxShareInfo")
      if (title || imgUrl || description) {
        return {
          title: title,
          imageUrl: imgUrl,
          path: '/packageI/redeem_code/index/index?id=' + this.data.id + '&code_id=' + this.data.code_id
        }
      }
    }else{
      return {
        title: this.data.details.share_title,
        imageUrl: this.data.details.share_icon,
        path: '/packageI/redeem_code/index/index?id=' + this.data.id + '&code_id=' + this.data.code_id
      }
    }


  }
})